<template>
  <view class="page-main">
    <view class="header">
      <image class="" :src="logoSrc" style="width: 100%; height: 100%"></image>
    </view>
    <view style="padding: 20rpx; display: flex">
      <view
        class="coach-info"
        style="height: 120rpx; border-radius: 20rpx; width: 100vw"
      >
        <image
          class="coach-avatar"
          :src="avatarUrl || '../../static/logo1.png'"
          style="width: 120rpx; height: 120rpx"
          @click="uploadAvatar"
        ></image>
        <view class="coach-details">
          <view class="coach-name" @click="openEditModal">
            {{ userName || "客户名称" }}
          </view>
        </view>
      </view>
    </view>

    <view class="plan-info" style="border-radius: 20rpx; margin: 20rpx">
      <view class="plan-item" style="display: flex; align-items: center" @click="openCountEditModal">
        <view
          class="plan-details"
          style="
            display: flex;
            flex-direction: column;
            justify-content: space-between;
          "
        >
          <view class="plan-title" style="align-self: flex-start">
            累积训练总次数
          </view>
          <view class="plan-number tc" style="align-self: center">
            {{ numInfo.total || 0}}
          </view>
        </view>
      </view>
      <view class="plan-item" style="display: flex; align-items: center">
        <view
          class="plan-details"
          style="
            display: flex;
            flex-direction: column;
            justify-content: space-between;
          "
        >
          <view class="plan-title" style="align-self: flex-start">
            本周训练次数
          </view>
          <view class="plan-number tc" style="align-self: center">
            {{ numInfo.week || 0}}
          </view>
        </view>
      </view>
    </view>

    <view
      style="
        padding: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      "
    >
      <view
        class="plan-name-section tc"
        style="
          background-color: #000;
          color: #fff;
          padding: 20rpx;
          border-radius: 20rpx;
          width: 60%;
        "
      >
        <text class="tc">{{ planName }}</text>
      </view>
    </view>

    <div
      style="
        margin: -70rpx 20rpx 20rpx 20rpx;
        padding: 60rpx 20rpx 20rpx 20rpx;
        background: #fff;
        border-radius: 20rpx;
      "
    >
      <div v-for="(item, index) in dataList" :key="index">
        <view class="f ac xb mt20r">
          <view
            class="title f ac xb rds20r"
            style="
              background-color: #000;
              color: #fff;
              padding: 20rpx;
              width: 50%;
            "
          >
            <div style="display: flex; align-items: center">
              <image
                class=""
                src="../../static/xl.png"
                style="width: 50rpx; height: 50rpx;margin-right: 10rpx;"
                lazy-load="false"
                binderror=""
                bindload=""
              ></image>
              {{ item.purpose }}
            </div>
          </view>
        </view>
        <div v-if="item.exercises && item.exercises.length > 0">
          <view
            v-for="(exercise, eIndex) in item.exercises"
            :key="eIndex"
            class="f ac xb mt30r plan chooseitem mt20r"
          >
            <view class="exercise-name tc" style="flex: 1; text-align: center">
              <text class="tc">{{ exercise.name }}</text>
            </view>
            <view class="f ac xc tc" style="flex: 1; text-align: center">
              <div class="tc">
                {{ exercise.sets }} 组 X {{ exercise.reps.count
                }}{{ getUnitLabel(exercise.reps.unit) }}
              </div>
            </view>
            <view class="f ac xc tc" style="flex: 1; text-align: center">
              <div class="tc">{{ exercise.weighs }}</div>
            </view>
          </view>
        </div>
        <div v-else class="f ac xc mt30r plan chooseitem mt20r">暂无动作</div>
      </div>
    </div>
    <view class="add-button">
      <u-button
        @click="sharePlan"
        color="#000"
        text="分享计划"
        shape="circle"
        open-type="share"
      ></u-button>
    </view>

    <!-- 弹窗 -->
    <view class="modal" v-if="showModal" @click.stop="closeModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">修改名称</text>
          <text class="close-btn" @click="closeModal">×</text>
        </view>
        <input
          style="width: 90%;"
          v-model="userName"
          class="modal-input"
          placeholder="请输入新名称"
        />
        <view class="modal-footer" style="justify-content: space-between; width: 100%;">
          <view class="share-button" @click="closeModal" style="flex: 1; margin-right: 10rpx;">取消</view>
          <view class="share-button" @click="updateNickname" style="flex: 1; margin-left: 10rpx;">确认</view>
        </view>
      </view>
    </view>

    <!-- 修改训练总次数弹窗 -->
    <view class="modal" v-if="showCountModal" @click.stop="closeCountModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">修改累积训练总次数</text>
          <text class="close-btn" @click="closeCountModal">×</text>
        </view>
        <input
          v-model="newCount"
          class="modal-input"
          placeholder="请输入新的训练总次数"
          type="number"
          style="width: 90%;"
        />
        <view class="modal-footer" style="justify-content: space-between; width: 100%;">
          <view class="share-button" @click="closeCountModal" style="flex: 1; margin-right: 10rpx;">取消</view>
          <view class="share-button" @click="updateCount" style="flex: 1; margin-left: 10rpx;">确认</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { planDetails, getUserInfo, edit_customer,getCount,customerDetail,editCount} from "../../api/fit";
export default {
  data() {
    return {
      logoSrc: "../../static/logo1.png",
      id: 0,
      planName: "",
      userName:'',
      dataList: [],
      unitOptions: [
        { label: "次", value: "c" },
        { label: "秒", value: "s" },
        { label: "分", value: "m" },
      ],
      showModal: false, // 控制弹窗显示
      customerId:'',
      numInfo:{},
      userInfo:{},
      avatarUrl: '',
      showCountModal: false, // 控制修改次数弹窗显示
      newCount: '', // 新的训练总次数
    };
  },
  onLoad(options) {
    this.id = options.id;
    this.customerId = options.customerId;
    this.getInfo();
    this.getUserInfo();
    this.getNum()
    this.getDetail()
    this.userName = options.name;
  },
  onShareAppMessage(res) {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: this.planName || "训练计划",
      path: `/pages/customer/plandetail?id=${this.id}&customerId=${this.customerId}`,
    };
  },
  methods: {
    getDetail(){
      customerDetail(this.customerId).then(res=>{
        console.log(res,'res');
        this.$set(
          this,
          "avatarUrl",
          res.data.picture
            ? `https://api.itaster.cn/file/${res.data.picture}`
            : "../../static/logo1.png"
        );
        this.$set(this,'userName',res.data.compellation)
      })
    },
    async getNum(){
      const res = await getCount(this.customerId);
      this.numInfo = res.data
    },
    async getUserInfo() {
      // try {
      //   const res = await getUserInfo();
      //   const { user, tenantEntity } = res.data;
      //   this.$set(
      //     this,
      //     "logoSrc",
      //     tenantEntity.background
      //       ? `https://api.itaster.cn/file/${tenantEntity.background}`
      //       : "../../static/logo1.png"
      //   );
 
      // } catch (err) {
      //   console.error("报错了", err);
      // }
    },
    async getInfo() {
      const res = await planDetails(this.id);
      this.dataList = res.data.nodes;
      this.planName = res.data.planName;
    },

    getUnitLabel(unit) {
      const option = this.unitOptions.find((opt) => opt.value === unit);
      return option ? option.label : "";
    },

    sharePlan() {
      // uni.share({
      //   provider: 'weixin',
      //   scene: 'WXSceneSession', // 分享到微信好友
      //   ...shareData,
      //   success: () => {
      //     uni.showToast({
      //       title: '分享成功',
      //       icon: 'success',
      //     });
      //   },
      //   fail: (err) => {
      //     console.error('分享失败:', err);
      //     uni.showToast({
      //       title: '分享失败，请重试',
      //       icon: 'none',
      //     });
      //   },
      // });
    },

    async uploadAvatar() {
      const that = this;
      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: async function (res) {
          const tempFilePaths = res.tempFilePaths;
          const uploadRes = await uni.uploadFile({
            url: "https://api.itaster.cn/api/common/upload", // 替换为你的上传接口
            filePath: tempFilePaths[0],
            name: "file",
            header: {
              Authorization: "Bearer " + uni.getStorageSync("token"),
            },
          });
          const data = JSON.parse(uploadRes.data);
          if (data.code === 200) {
            that.avatarUrl = "https://api.itaster.cn/file/" + data.message;
            await that.updateUserInfo(data.message);
          } else {
            uni.showToast({
              title: "上传失败",
              icon: "none",
            });
          }
        },
      });
    },

    async updateUserInfo(avatarUrl) {
      try {
        const res = await edit_customer({ id: this.customerId,picture: avatarUrl }); // 调用 edit_customer 接口
        if (res.code === 200) {
          uni.showToast({
            title: "头像更新成功",
            icon: "success",
          });
          this.getDetail();
        } else {
          uni.showToast({
            title: "头像更新失败",
            icon: "none",
          });
        }
      } catch (err) {
        console.error(err);
        uni.showToast({
          title: "头像更新失败",
          icon: "none",
        });
      }
    },

    openEditModal() {
      this.showModal = true; // 打开弹窗
    },
    closeModal() {
      this.showModal = false; // 关闭弹窗
    },
    async updateNickname() {
      this.showModal = false; // 关闭弹窗
      try {
        const res = await edit_customer({ id: this.customerId, compellation: this.userName });
        if (res.code === 200) {
          uni.showToast({
            title: "名称更新成功",
            icon: "success",
          });
          this.getUserInfo();
        } else {
          uni.showToast({
            title: "名称更新失败",
            icon: "none",
          });
        }
      } catch (err) {
        console.error("更新名称失败:", err);
        uni.showToast({
          title: "更新失败，请重试",
          icon: "none",
        });
      }
    },
    openCountEditModal() {
      this.newCount = this.numInfo.total || 0; // 设置当前总次数为输入框的初始值
      this.showCountModal = true; // 打开弹窗
    },
    closeCountModal() {
      this.showCountModal = false; // 关闭弹窗
    },
    async updateCount() {
      try {
        const res = await editCount({
          customerId: this.customerId,
          count: this.newCount,
        });
        if (res.code === 200) {
          uni.showToast({
            title: "训练总次数更新成功",
            icon: "success",
          });
          this.getNum(); // 更新训练次数信息
          this.closeCountModal(); // 关闭弹窗
        } else {
          uni.showToast({
            title: "训练总次数更新失败",
            icon: "none",
          });
        }
      } catch (err) {
        console.error("更新训练总次数失败:", err);
        uni.showToast({
          title: "更新失败，请重试",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss">
.header {
  height: 40vh;
  position: relative;
  z-index: 1;
}
.chooseitem {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border: 1px solid #ebebeb;
  border-radius: 20rpx;
  background-color: #fff;
}

.page-main {
  background-color: #efefef;
  padding-bottom: 100rpx;
}

.plan-name-section {
  height: 60rpx;
  line-height: 60rpx;
  background-color: #000;
  color: #fff;
  font-size: 40rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 16rpx;
}

.input-label {
  font-size: 28rpx;
  color: #fff;
  margin-right: 20rpx;
  white-space: nowrap;
}

.exercise-name {
  position: relative;
  min-width: 200rpx;
}

.add-button {
  position: fixed;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 70%;
  z-index: 1000;
  padding: 10rpx;
}
.coach-info {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  margin-top: -90rpx; /* 调整此值以上移 coach-info */

  z-index: 999; /* 确保 z-index 较高 */
  .coach-avatar {
    border-radius: 50%;
  }
  .coach-details {
    margin-left: 130rpx;
    .coach-name {
      font-size: 64rpx;
      font-weight: bold;
    }
  }
  .contact-service {
    font-size: 28rpx;
    color: #fff;
    background: #000;
    white-space: inherit;
    border-radius: 20rpx;
    display: inline-block;
  }
}

.plan-info {
  display: flex;
  justify-content: space-around;
  padding: 20rpx;
  background: #fff;
  margin: 20rpx 0; /* 上下边距 */

  .plan-item {
    display: flex;
    align-items: flex-start;

    .plan-icon {
      margin-right: 10rpx;
    }

    .plan-details {
      .plan-title {
        font-size: 28rpx;
        color: #333;
      }

      .plan-number {
        font-size: 80rpx;
        font-weight: bold;
        color: #000;
        margin-top: 10rpx;
      }
    }
  }
}

.coach-name-input {
  font-size: 64rpx; /* 确保输入字体大小与显示字体一致 */
  border: 1px solid #ccc; /* 添加边框 */
  border-radius: 10rpx; /* 圆角边框 */
  padding: 10rpx; /* 内边距 */
  width: 100%; /* 使输入框宽度占满 */
  background: #f8f8f8; /* 背景色 */
  transition: border-color 0.3s; /* 添加过渡效果 */

  &:focus {
    border-color: #007bff; /* 聚焦时边框颜色 */
    outline: none; /* 去掉默认的轮廓 */
    background: #fff; /* 聚焦时背景色 */
  }
}

.coach-name {
  font-size: 64rpx; /* 确保显示字体大小与输入字体一致 */
  font-weight: bold; /* 加粗 */
  color: #333; /* 字体颜色 */
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.modal-content {
  width: 80%;
  background: white;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
  min-height: 200rpx; /* 增加最小高度 */
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;

  .modal-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
  }

  .close-btn {
    font-size: 28rpx;
    color: #999;
    cursor: pointer;
  }
}

.modal-input {
  font-size: 28rpx; /* 输入框字体大小 */
  border: 1px solid #ccc; /* 边框 */
  border-radius: 10rpx; /* 圆角 */
  padding: 10rpx; /* 内边距 */
  width: 100%; /* 宽度占满 */
  background: #f8f8f8; /* 背景色 */
  margin-bottom: 20rpx; /* 底部间距 */
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx; /* 添加顶部间距 */
}

.share-button {
  background-color: #000; /* 分享计划的背景色 */
  color: #fff; /* 分享计划的文字颜色 */
  padding: 10rpx 20rpx; /* 内边距 */
  border-radius: 20rpx; /* 圆角 */
  text-align: center; /* 文字居中 */
  cursor: pointer; /* 鼠标指针样式 */
}
</style>
